<template>
	<view>
		<view class="zaiui-bar-search-title-box">
			<view class="cu-bar fixed no-shadow bg-white">
				<view class="action" @tap="BackPage">
					<text class="cuIcon-back"/>
				</view>
				<view class="content search">
						<view class="search-form round">
							<text class="cuIcon-search"/>
							<input 
								class="margin-left-xs" 
								placeholder="输入您正在找的宝贝" 
								v-model="searchText" 
								@input="onSearchInput"
								placeholder-class="placeholder-style"
							/>
							<text class="cuIcon-close text-gray" v-if="searchText" @tap="clearSearch"/>
						</view>
					</view>
			</view>
			<!--占位的-->
			<view class="zaiui-seat-height"/>
		</view>
		
		<view class="VerticalBox">
			<scroll-view class="VerticalNav nav" scroll-y scroll-with-animation :scroll-top="verticalNavTop">
				<block v-for="(item,index) in list" :key="index">
					<view class="cu-item" :class="index==tabCur?'text-red cur':''" @tap="TabSelect" :data-id="index">
						<view class="category-item" :class="index==tabCur?'text-black text-bold':''">
							<text class="cuIcon-title text-red margin-right-sm" v-if="index==tabCur"/>
							{{item.name}}
						</view>
					</view>
				</block>
			</scroll-view>
			<scroll-view class="VerticalMain" scroll-y scroll-with-animation :scroll-into-view="'main-'+mainCur" @scroll="VerticalMain">
				<!--热门分类区域-->
				<view class="padding-top padding-lr" id="main-hot">
					<view class="cu-bar bg-white">
						<view class="action">
							<text class="cuIcon-hot text-red"/>
							<text>热门分类</text>
						</view>
					</view>
					<view class="zaiui-grid-icon-box">
						<view class="cu-list grid col-4 no-border">
							<block v-for="(item,index) in hotCategories" :key="index">
								<view class="cu-item sub-category-item hot-category" @tap="subCategoryTap" :data-category="item">
									<view class="grid-icon">
										<image class="icon" :src="item.icon || item.img" lazy-load mode="aspectFit"/>
										<text class="cuIcon-hot text-red hot-badge"/>
									</view>
									<text class="text-black text-sm text-cut">{{item.name}}</text>
								</view>
							</block>
						</view>
					</view>
				</view>
				
				<!--推荐分类区域-->
				<view class="padding-top padding-lr" id="main-recommend">
					<view class="cu-bar bg-white">
						<view class="action">
							<text class="cuIcon-like text-red"/>
							<text>推荐分类</text>
						</view>
					</view>
					<view class="zaiui-grid-icon-box">
						<view class="cu-list grid col-4 no-border">
							<block v-for="(item,index) in recommendedCategories" :key="index">
								<view class="cu-item sub-category-item recommend-category" @tap="subCategoryTap" :data-category="item">
									<view class="grid-icon">
										<image class="icon" :src="item.icon || item.img" lazy-load mode="aspectFit"/>
										<text class="cuIcon-like text-red recommend-badge"/>
									</view>
									<text class="text-black text-sm text-cut">{{item.name}}</text>
									<text class="text-gray text-xs text-cut" v-if="item.desc">{{item.desc}}</text>
								</view>
							</block>
						</view>
					</view>
				</view>
				
				<block v-for="(item,index) in list" :key="index">
					<view class="padding-top padding-lr" :id="'main-'+index">
						
						<!--标题栏-->
						<view class="cu-bar bg-white">
							<view class="action">
								<text class="cuIcon-title text-red"/>
								<text>标题栏-{{item.name}}</text>
							</view>
						</view>
						
						<!--子分类图标导航-->
						<view class="zaiui-grid-icon-box">
							<view class="cu-list grid col-4 no-border">
								<block v-for="(items,indexs) in sortList" :key="indexs">
									<view class="cu-item sub-category-item" @tap="subCategoryTap" :data-category="items">
										<view class="grid-icon">
											<image class="icon" :src="items.icon || items.img" lazy-load mode="aspectFit"/>
										</view>
										<text class="text-black text-sm text-cut">{{items.name}}</text>
									</view>
								</block>
							</view>
						</view>
						
					</view>
				</block>
			</scroll-view>
		</view>
		
	</view>
</template>

<script>
	import _sort_data from '@/api/categorys.js';	//虚拟数据
	import _tool from '@/utils/tools.js';	//工具函数
	
	export default {
		data() {
			return {
				list: [], tabCur: 0, mainCur: 0, verticalNavTop: 0, load: true, sortList: [],
				searchText: '', // 搜索文本
				originalSortList: [], // 原始子分类列表
				isSearching: false, // 是否正在搜索
				hotCategories: [], // 热门分类
				recommendedCategories: [], // 推荐分类,
			}
		},
		async onLoad() {
			
			// 获取完整的分类树数据 - 优先从store中获取
			let categoryTree = this.$store.getters['category/getCategoryTree'];
			if (!categoryTree || categoryTree.length === 0) {
				// 如果store中没有数据，从API获取
				categoryTree = await _sort_data.getCategoryTree();
			}
			
			this.list = categoryTree;
			this.listCur = categoryTree[0];
			this.originalSortList = categoryTree[0].subCategories || [];
			
			// 默认显示第一个分类的子分类
			if (categoryTree.length > 0) {
				this.sortList = this.originalSortList;
			}
			
			// 获取热门分类和推荐分类 - 优先从store中获取
			let hotCategories = this.$store.getters['category/getHotCategories'];
			let recommendedCategories = this.$store.getters['category/getRecommendedCategories'];
			
			if (!hotCategories || hotCategories.length === 0) {
				hotCategories = await _sell_data.getHotCategories();
			}
			if (!recommendedCategories || recommendedCategories.length === 0) {
				recommendedCategories = await _sell_data.getRecommendedCategories();
			}
			
			this.hotCategories = hotCategories;
			this.recommendedCategories = recommendedCategories;
		},
		onReady() {
			_tool.setBarColor(true);
			uni.pageScrollTo({
			    scrollTop: 0,
			    duration: 0
			});
		},
		methods: {
			BackPage() {
				uni.navigateBack();
			},
			TabSelect(e) {
		const index = e.currentTarget.dataset.id;
		this.tabCur = index;
		this.mainCur = index;
		this.verticalNavTop = (index - 1) * 50;
		
		// 切换分类时更新子分类显示
		if (this.list[index] && this.list[index].subCategories) {
			this.originalSortList = this.list[index].subCategories;
			// 如果正在搜索，保持搜索结果，否则显示原始分类
			if (!this.isSearching) {
				this.sortList = this.originalSortList;
			}
		}
	},
			VerticalMain(e) {
				// #ifdef MP-ALIPAY
				   return false  //支付宝小程序暂时不支持双向联动 
				// #endif
				let that = this;
				let tabHeight = 0;
				if (this.load) {
					for (let i = 0; i < this.list.length; i++) {
						let view = uni.createSelectorQuery().select("#main-" + this.list[i].id);
						view.fields({
							size: true
						}, data => {
							this.list[i].top = tabHeight;
							tabHeight = tabHeight + data.height;
							this.list[i].bottom = tabHeight;
						}).exec();
					}
					this.load = false
				}
				let scrollTop = e.detail.scrollTop + 10;
				for (let i = 0; i < this.list.length; i++) {
					if (scrollTop > this.list[i].top && scrollTop < this.list[i].bottom) {
						this.verticalNavTop = (this.list[i].id - 1) * 50
						this.tabCur = this.list[i].id
						console.log(scrollTop)
						return false
					}
				}
			},
			searchTap() {
				uni.navigateTo({
					url: "/pages/home/search"
				});
			},
			
			// 子分类点击事件
			async subCategoryTap(e) {
				const category = e.currentTarget.dataset.category;
				console.log('选择子分类:', category);
				
				// 使用store记录选中的分类
				await this.$store.dispatch('category/selectCategory', category.id);
				
				// 询问用户是否要发布该分类的商品
				uni.showModal({
					title: '选择分类',
					content: `您选择了"${category.name}"分类，是否要发布该分类的商品？`,
					confirmText: '发布商品',
					cancelText: '查看商品',
					success: (res) => {
						if (res.confirm) {
							// 跳转到发布页面，传递分类信息
							uni.navigateTo({
								url: `/pages/goods/publish?category=${category.id}`
							});
						} else {
							// 跳转到分类列表页面，传递分类信息
							uni.navigateTo({
								url: `/pages/home/sort_list?category=${category.id}`
							});
						}
					}
				});
			},
			
			// 搜索输入事件
			onSearchInput(e) {
				const searchText = e.detail.value.trim();
				this.searchText = searchText;
				
				if (searchText === '') {
					// 清空搜索，显示原始分类
					this.isSearching = false;
					this.sortList = this.originalSortList;
				} else {
					// 执行搜索
					this.performSearch(searchText);
				}
			},
			
			// 执行搜索
			performSearch(searchText) {
				this.isSearching = true;
				
				// 在所有分类中搜索匹配的子分类
				const allSubCategories = [];
				this.list.forEach(category => {
					if (category.subCategories) {
						allSubCategories.push(...category.subCategories);
					}
				});
				
				// 过滤匹配的子分类
				const filteredCategories = allSubCategories.filter(item => {
					return item.name.toLowerCase().includes(searchText.toLowerCase());
				});
				
				this.sortList = filteredCategories;
			},
			
			// 清空搜索
			clearSearch() {
				this.searchText = '';
				this.isSearching = false;
				this.sortList = this.originalSortList;
			},
			
			// 搜索页面跳转（保留原有功能）
			searchTap() {
				uni.navigateTo({
					url: "/pages/home/search"
				});
			}
		}
	}
</script>

<style lang="scss">
	/* #ifdef APP-PLUS */
		@import "../../static/colorui/main.css";
		@import "../../static/colorui/icon.css";
		@import "../../static/zaiui/style/app.scss";
	/* #endif */
	
	@import "../../static/zaiui/style/sort_vue.scss";
	
</style>
